package com.school.base.action.admin;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.school.base.model.Admin;
import com.school.base.service.AdminService;
import com.school.common.base.BaseAction;
import com.school.common.constant.Constant;
import com.school.common.util.Md5Utils;
import com.school.common.util.SpringUtils;

public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 3754030906030479124L;
	private static Logger logger = Logger.getLogger(LoginAction.class);
	private static AdminService service = (AdminService) SpringUtils.getBean("base_adminService");
	private String loginName;
	private String pwd;
	private String validateCode;

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	public String login() {
		return SUCCESS;
	}

	public String loginDo() {
		if (validateCode == null || validateCode.isEmpty()) {
			this.addActionError("请输入验证码");
			return INPUT;
		}
		if (!checkValidateCode(validateCode)) {
			this.addActionError("验证码错误，请重新输入");
			return INPUT;
		}
		if (loginName == null || loginName.isEmpty()) {
			this.addActionError("请输入用户名");
			return INPUT;
		}
		if (pwd == null || pwd.isEmpty()) {
			this.addActionError("请输入密码");
			return INPUT;
		}
		Admin admin = null;
		try {
			admin = service.check(loginName, Md5Utils.getMd5(pwd));
		} catch (Exception e) {
			this.addActionError(e.getMessage());
			return INPUT;
		}
		if (admin == null) {
			this.addActionError("登录失败，用户名或密码错误");
			return INPUT;
		}
		HttpSession session = this.getHttpSession();
		session.invalidate();
		session = this.getHttpServletRequest().getSession(true);
		session.setAttribute(Constant.SESSION_KEY_ADMIN, admin);
		return SUCCESS;
	}

	public String logout() {
		this.getHttpSession().invalidate();
		return SUCCESS;
	}

	private boolean checkValidateCode(String validateCode) {
		Object sessionCode = this.getHttpSession().getAttribute(Constant.IMG_VALIDATE_NAME);
		this.getHttpSession().removeAttribute(Constant.IMG_VALIDATE_NAME);
		if (validateCode.equals(sessionCode)) {
			return true;
		}
		return false;
	}
}
